package com.zz.framework.core.ext

import android.content.ClipData
import androidx.annotation.StringRes
import com.zz.framework.core.BaseApp
import java.net.URLEncoder
import java.util.regex.Pattern
import kotlin.experimental.and

/**
 * Copyright © 2019 zanezhao All rights reserved.
 * Created by zanezhao on 2019-11-14 10:55.
 *
 * @author: zanezhao 1820022519@qq.com
 * @version: V1.0
 */
fun String?.getLong(): Long {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return 0L
    }
    return try {
        java.lang.Long.parseLong(this.trim { it <= ' ' })
    } catch (e: Exception) {
        0L
    }
}

fun String?.getFloat(): Float {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return 0f
    }
    return try {
        this.trim { it <= ' ' }.toFloat()
    } catch (e: Exception) {
        0f
    }
}

fun String?.getDouble(): Double {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return 0.0
    }
    return try {
        this.trim { it <= ' ' }.toDouble()
    } catch (e: Exception) {
        0.0
    }
}

fun String?.getInt(): Int {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return 0
    }
    return try {
        Integer.parseInt(this.trim { it <= ' ' })
    } catch (e: Exception) {
        0
    }
}

fun String?.camelToUnderline(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    val len = this.length
    val sb = StringBuilder(len)
    for (i in 0 until len) {
        val c = this.get(i)
        if (Character.isUpperCase(c)) {
            sb.append("_")
            sb.append(Character.toLowerCase(c))
        } else {
            sb.append(c)
        }
    }
    return sb.toString()
}


fun String?.underlineToCamel(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    val len = this.length
    val sb = StringBuilder(len)
    var i = 0
    while (i < len) {
        val c = this.get(i)
        if (c == '_') {
            if (++i < len) {
                sb.append(Character.toUpperCase(this.get(i)))
            }
        } else {
            sb.append(c)
        }
        i++
    }
    return sb.toString()
}

fun String?.underlineToCamel2(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    val sb = StringBuilder(this)
    val mc = Pattern.compile("_").matcher(this)
    var i = 0
    while (mc.find()) {
        val position = mc.end() - i++
        sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase())
    }
    return sb.toString()
}

/**
 * if [String.isNullOrEmpty], invoke f()
 * otherwise invoke t()
 */
fun <T> String?.notNull(f: () -> T, t: () -> T): T {
    return if (isNullOrEmpty()) f() else t()
}

/**
 * whether string only contains digits
 */
fun String.areDigitsOnly() = matches(Regex("[0-9]+"))

/**
 * 是否是手机号
 */
fun String.isPhone() = "^[1][0-9]{10}$".toRegex().matches(this)
//fun String.isPhone() = "^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$".toRegex().matches(this)

/**
 * 是否是邮箱地址
 */
fun String.isEmail() = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?".toRegex().matches(this)

/**
 * 是否是身份证号码
 */
fun String.isIDCard() = "[1-9]\\d{16}[a-zA-Z0-9]".toRegex().matches(this)

/**
 * 是否是中文字符
 */
fun String.isChinese() = "^[\u4E00-\u9FA5]+$".toRegex().matches(this)


fun String.copy() {
    val clipData = ClipData.newPlainText(
        null,
        this
    )
    BaseApp.context.clipboardManager?.setPrimaryClip(clipData)
}


fun String.substring(startStr: String = "", endStr: String = ""): String {
    val start = if (startStr.isEmpty()) {
        0
    } else {
        this.indexOf(startStr) + startStr.length
    }
    val end = if (endStr.isEmpty()) {
        this.length
    } else {
        this.indexOf(endStr)
    }
    return this.substring(start, end)
}

fun Any.getStringExt(@StringRes resId: Int): String {
    return BaseApp.context.getString(resId)
}

fun String?.urlEncode() = URLEncoder.encode(this ?: "", "UTF-8")

//数字转中文
fun String?.toChinese(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    val sb = StringBuilder()
    for (i in 0 until this.length) {
        val c = this[i]
        if (c >= '0' && c <= '9') {
            sb.append("零一二三四五六七八九"[c - '0'])
        } else {
            sb.append(c)
        }
    }
    return sb.toString()
}

fun ByteArray.toHexString(withPrefix: Boolean = true): String {
    val stringBuilder = StringBuilder()
    if (withPrefix) {
        stringBuilder.append("0x")
    }
    for (element in this) {
        stringBuilder.append(String.format("%02x", element and 0xFF.toByte()))
    }
    return stringBuilder.toString()
}


fun String.hexStringToByteArray(): ByteArray {
    val HEX_CHARS = "0123456789ABCDEF"
    val result = ByteArray(length / 2)
    for (i in 0 until length step 2) {
        val firstIndex = HEX_CHARS.indexOf(this[i].toUpperCase());
        val secondIndex = HEX_CHARS.indexOf(this[i + 1].toUpperCase());
        val octet = firstIndex.shl(4).or(secondIndex)
        result.set(i.shr(1), octet.toByte())
    }
    return result
}

//移除字符串最后一个空格
fun String?.removeLastSpace(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    if (this.getLastChar() != " ") {
        return this
    }
    return this.substring(0, this.length - 1)
}

//获取字符串最后一个字符
fun String?.getLastChar(): String {
    if (this == null || "" == this.trim { it <= ' ' }) {
        return ""
    }
    return this.substring(this.length - 1, this.length)
}